package com.yc.login.web;

import com.google.gson.Gson;
import com.yc.login.vo.Result;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginInterceptor implements HandlerInterceptor {

    //前置拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        if (session.getAttribute("loginedUser") == null) {
            String accept = request.getHeader("Accept");
            if(accept.startsWith("application/json")){
                //Json
                Gson gson = new Gson();
                String json = gson.toJson(new Result(0,"请先登录！",null));
                response.setContentType("application/json;charset=utf-8");
                response.getWriter().append(json);
            }else {
                //工程的路径前缀  contextPath  /
                String contextPath = request.getServletContext().getContextPath();
                String indexPath = contextPath + "/index.html?toLogin";
                response.sendRedirect(indexPath);   //浏览器端解析  若加/ 则是从8080后面拼接
                //阻止请求到达目标资源
            }
            return false;
        }
        return true;
    }

    //后置拦截
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//        System.out.println("===================================postHandle=======================================");
    }

    //完成拦截
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        System.out.println("===================================afterHandle=======================================");
    }
}
